package cn.cjxy.userms.controller;

import cn.cjxy.userms.entity.User;
import cn.cjxy.userms.service.UserService;
import cn.cjxy.userms.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/add")
public class AddServlet extends HttpServlet {
    //注入service层
    UserService userService=new UserServiceImpl();
    /**
     * 处理添加用户相关信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //防止乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        //获取表单中的user
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Integer gender = Integer.valueOf(req.getParameter("gender"));
        Integer age = Integer.valueOf(req.getParameter("age"));
        String address = req.getParameter("address");
        //将user的信息存入到实体
        User user = new User(null,username,password,gender,age,address);
        int i = userService.addUser(user);
        //判断新增成功与否
        if (i==1){//新增成功
            //返回list页面 让它重新加载数据
            resp.sendRedirect("/list");
        }else {
            //返回add.jsp页面
            resp.sendRedirect("/add.jsp");
        }
    }
}
